#include <math.h>
#include <stdlib.h>
#include <time.h>
#include "key.h"
#include "draw.h"
#include "terrain.h"
#include "texture1.h"
#include "definitions.h"
#include "toolkits/includes/glut.h"
#include "toolkits/includes/glm.h"
#include "toolkits/includes/il.h"

extern GLfloat currentColor[3];
extern GLMmodel *key;
extern float keyList[KEYS][3];
extern int capturedKeys[KEYS];
extern int keyIDOnRadar;
extern int keysSoFar;
extern time_t timeNow;
extern float heightMap[TERRAINLENGTH*2][TERRAINLENGTH*2];

Key::Key() {
}

void Key::drawKey() {
	glPushMatrix();
	glTranslatef(0.0,0.5,0.0);
		float color[] = {1.0,0.0,1.0,1.0};
		glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,color);
		Draw::setColor(1.0,0.0,1.0);
		glmDraw(key, GLM_MATERIAL | GLM_SMOOTH);

		glColor3fv(currentColor);
	glPopMatrix();
}

void Key::placeKeys() {
	float r = 0.0;
	float alpha;
	float rr;
	float x,z,y;
  
	srand(timeNow % 3600); 
	//srand(31457);
	int keys = 0;
  
	while (keys < KEYS) {

		rr = rand() * 2050.0/ RAND_MAX;
		alpha = rand() * 6.28 / RAND_MAX;

		x = cos(alpha) * (rr + r);
		z = sin(alpha) * (rr + r);
		//float pos[3] = {x,0,z};

		/*if (fabs(x) < TERRAINLENGTH && fabs(z) < TERRAINLENGTH && !comparePosition(0, keys, pos)) {*/
		if (fabs(x) < TERRAINLENGTH && fabs(z) < TERRAINLENGTH) {
    //if (fabs(x) < heightW && fabs(z) < heightH && x > 0.0f && z > 0.0f) {
			if (!capturedKeys[keys]) { 
        y = heightMap[(int)x + TERRAINLENGTH][(int)z + TERRAINLENGTH];
				glPushMatrix();
				glTranslatef(x, y,z);
				insertKey(keys, x, y, z);
				drawKey();
				glPopMatrix();
			}
			keys++;
		}
	}

	/*for(int i=0;i<KEYS;i++) {
	printf("id:%d\t\tx:%f\tz:%f\n",keyList[i].id,keyList[i].pos[0],keyList[i].pos[2]);
	}*/
}

int Key::calcCapturedKeys() {
	int total = 0, i = 0;
	for(i = 0; i < KEYS; i++)
		if(capturedKeys[i] == 1)
			total++;
	return total;
}

void Key::insertKey(int id, float x, float y, float z){
	//keyList[id].id		= id;
	keyList[id][0]	= x;
	keyList[id][1]	= y;
	keyList[id][2]	= z;
}